package lego.jbv;

import lejos.util.Delay;

public class Exhaustion extends Thread {
	private final int LEVEL_HIGH = 0, LEVEL_NORMAL = 1, LEVEL_INC = 2;
	private boolean stopNow = false;
	private int lastLevel = -1;
	private boolean newLevel = false;
	private Driver driver;
	
	public Exhaustion(Driver driver)
	{
		this.driver = driver;
		setDaemon(true);
	}

	public void run() {
		while (!stopNow) {
			//Decrease stamina fast
			if (driver.getSpeed() > Display.getNormalSpeed()) {
				Display.setStamina(Display.getStamina() - 2);
				
				validateLevel(LEVEL_HIGH);
			}

			//Decrease stamina
			else if (driver.getSpeed() > 10) {
				Display.setStamina(Display.getStamina() - 1);
				
				validateLevel(LEVEL_NORMAL);
			}
			
			//Increase stamina
			else
			{
				if(Display.getStamina() <= 95)
				{
					Display.setStamina(Display.getStamina()+5);
				}
				
				else
				{
					Display.setStamina(100);
				}
				
				validateLevel(LEVEL_INC);
			}
			
			if(newLevel)
			{
				adjustSpeed();
				newLevel = false;
			}
			
			Delay.msDelay(500);
		}
	}

	public void stop() {
		stopNow = true;
	}
	
	private void validateLevel(int level)
	{
		if(lastLevel != level)
		{
			newLevel = true;
			lastLevel = level;
		}
	}
	
	private void adjustSpeed()
	{
		//High stamina --> high speed
		if(Display.getStaminaHighBound() <= Display.getStamina())
		{
			driver.setMaxSpeed(Display.getBurstSpeed());
		}
		
		//Medium stamina --> normal speed
		else if(Display.getStaminaLowBound() <= Display.getStamina())
		{
			driver.setMaxSpeed(Display.getNormalSpeed());
		}
		
		//Low stamina --> slow speed
		else
		{
			driver.setMaxSpeed(Display.getNormalSpeed()/2);
		}
	}
}
